﻿using System.Numerics;
using System.Collections.Generic;
using System;
using UnityEngine;
using foundation;
using foundation.socket;
using System.Timers;
using System.Threading.Tasks;
using awaitTest;
using mao;
using foundation.events;
using System.IO;
using System.Text.RegularExpressions;

namespace Test
{

    class T
    {
        public float code = 0;
    }



    class Program
    {

        // public void LoadAll()
        // {
        //     foreach (var asset in assets)
        //     {
        //         var target = AmfHelper.read_object(asset.bytes) as Dictionary<string, object>;
        //     }
        // }
        static void Main(string[] args)
        {
            Facade.init();

            ClassUtils.Instance<HeartModel>();
            ClassUtils.Instance<ResModel>();
            ClassUtils.Instance<ChapterModel>();
            ClassUtils.Instance<DayModel>();
            ClassUtils.Instance<WeekModel>();
            ClassUtils.Instance<ItemModel>();

            // var pro = new T();
            // pro.code = 100;
            // float aaa = 100;
            // var amfBytes = AmfHelper.write_object(aaa);
            // object proobj = AmfHelper.read_object(amfBytes);
            // Console.WriteLine("?");
            // List<object> a = new List<object>();
            // a.Add(100);
            // var a = new int[] { 10 };
            // var amfBytes = AmfHelper.write_object(a);
            // AmfHelper.printBytes(amfBytes);
            // Console.WriteLine("...");

            // var bytea = AmfHelper.write_object("1215");
            // object a = AmfHelper.read_object(bytea);
            // double b = (double)Convert.ChangeType(a, typeof(double));
            // b = (double)Convert.ChangeType(b, typeof(double));
            // Console.WriteLine("...");

            // var amftype = typeof(ushort).FullName;
            // byte[] amfbytes = new byte[] { 9,3,1,4,100 };
            // var amfo = AmfHelper.read_object(amfbytes);
            // Console.WriteLine("...");

            // double d = 2;
            // var type = d.GetType();

            // Console.WriteLine("?");

            // Dictionary<uint, object> test = new Dictionary<uint, object>();
            // test.Add(0, 100);
            // var b = AmfHelper.write_object(test);
            // Console.Write(b);

            // var l = new O1LimitVO();
            // l.module = "res";
            // l.conditions = new List<O1ConditionVO>();
            // var v = new O1ConditionVO();
            // v.id = "100";
            // v.opera = "";
            // l.conditions.Add(v);

            // var objs = new object[1];
            // objs[0] = v;

            // var t = new T();
            // t.code = 1;
            // List<T> vcc = new List<T>();
            // vcc.Add(t);

            // List<short> vcc = new List<short>();
            // vcc.Add(1);
            // var bytes = AmfHelper.write_object(l.conditions);
            // var o = AmfHelper.read_object(bytes) ;
            // Console.WriteLine("Hello World!");

            // O1ConditionVO[] conditions;

            // var fi = (l.GetType()).GetField("limit");

            // conditions = DataConvert.ConvertObject(objs, fi.GetType());


            // object obj = new O1ConditionVO();
            // var t = obj.GetType();
            // var b = Convert.ChangeType(obj, t);


            // var bytes11 = File.ReadAllBytes("conf/movie.bytes");
            // var value11 = AmfHelper.read_object(bytes11);
            // var target = DataConvert.ObjectDictToVODict<Dictionary<string, HeroVO>>(value);
            // var o = target["1"] as AdVO;
            // var o = target["1"];
            // Console.WriteLine("Hello World!");

            var type = typeof(GameConfig);
            // var fields = type.GetFields();
            foreach (var item in Directory.GetFiles("conf/"))
            {
                var o = Regex.Match(item, ".*?/(.*?).bytes");
                Console.WriteLine("load " + item + "");
                // var o = Regex.Match(item, ".*?/(chapter).bytes");
                // var o = Regex.Match(item, ".*?/(task).bytes");
                if (null != o)
                {
                    var value = o.Groups[1].Value;
                    var info = type.GetField(value);
                    if (null != info)
                    {
                        var bytes = File.ReadAllBytes(item);
                        var target = AmfHelper.read_object(bytes) as Dictionary<string, object>;
                        var convalue = DataConvert.ObjectDictToVODict<object>(target, info.FieldType);
                        info.SetValue(null, convalue);
                    }
                }
            }


            // Console.WriteLine("");


            //var pvp_rank_season_reward = GameConfig.pvp_rank_season_reward["0"];
            // value.reward



            // var child = GameConfig.module["pro"].childs[1];
            // Console.WriteLine("Hello World!");


            // var data = new ASObject();
            // var hero = new ASObject();
            // var id = new ASObject();
            // var heroItem = new HeroItem();
            // // heroItem["lv"] = 10;
            // id["1"] = heroItem;
            // hero["id"] = id;
            // data["hero"] = hero;


            // object v = 1;
            // var n = Convert.ToString(v);


            // data["hero"] = new HeroData();


            // var log = new ASObject();
            // var to = new ClientData();
            // DataConvert.CopyProperty(data, to, log);
            // DataConvert.DispatchCopyEdit(log, to);

            var socket = MaoSocket.websocket;
            socket.isSync = false;
            socket.AddEventListener(SOCKET_EVENT.OPEN, socketConnect);
            // socket.Connect("ws://127.0.0.1:8888");
            socket.Connect("ws://mstlocal.winnfthero.io:666/h5?host=127.0.0.1&port=1885");

            // var t = new T();
            // t.code = 2;
            // var bytes = AmfHelper.write_object(t);
            // var o = AmfHelper.read_object(bytes);

            // foundation.events.EventTest.Test();
            // new EventAttributeTest().type = "whh";
            // new EventAttributeTest().type = "whh2";
            // Facade.EVT.SimpleDispatch("hello");
            // EventTest.Test();
            // Console.WriteLine("Hello World!");

            // Console.WriteLine("Hello World!");

            // _ = RunApp();

            // await Task.Delay(3000);

            // Socket.Set("crl");

            Console.ReadLine();
        }


        public async static void socketConnect(EventX eventX)
        {
            var vo = new LoginVO();
            vo.account = "youzi115";
            vo.serverId = 1200;
            var result = await MaoSocket.login(vo) as Login_atk;



            var client = HeartModel.client;

            // var jsonvalue = await MaoSocket.asyncToken(15, vo);

            // var req = new mine_pledge_req();
            // req.heroId = 1;
            // req.pledgeId = 1;

            // var req = new rank_match_list_req();
            // var ret = await MaoSocket.asyncToken(RankSocketConst.match_list, req);
            // mine_get_all_mine_res res = await MaoSocket.asyncToken(MineSocketConst.get_all_mine, null) as mine_get_all_mine_res;

            Console.WriteLine("??");

            // ASObject day = new ASObject();
            // day["login"] = 2;
            // ASObject taskitem = new ASObject();
            // taskitem["state"] = 1;

            // ASObject task = new ASObject();
            // ASObject taskid = new ASObject();
            // taskid["1"] = taskitem;
            // task["id"] = taskid;

            // ASObject data = new ASObject();
            // // data["day"] = day;
            // data["task"] = task;

            // ASObject log = new ASObject();

            // DataConvert.CopyProperty(data, client, log);


            // Console.WriteLine("??");

            // var chapter = GameConfig.chapter["1"].childs[0];
            // var task = GameConfig.task["1"];

            // O1LimitVO limit = new O1LimitVO();
            // limit.filter = new O1ConditionVO();
            // limit.filter.id = "id";
            // limit.filter.opera = "===";
            // limit.filter.value = 1;
            // O1ConditionVO condition = new O1ConditionVO();
            // condition.id = "count";
            // condition.opera = "+=";
            // condition.value = 1;
            // limit.conditions = new List<O1ConditionVO>();
            // limit.conditions.Add(condition);
            // limit.module = "item";

            // ClassUtils.Instance<ItemModel>().getLimitRewards(client, limit);

            // var v = BaseModel.getLimitRewards(HeartModel.client, task.condition);

            // Console.WriteLine("Hello World!");

            // await command("item_create", 1, 2);

            // await Hero_Test();
            // await ChapterTest();
            // await ChapterTest();
            // var conf = GameConfig.chapter["1"].childs[2];
            // Random rd = new Random();
            // await setProperty("res.energy", 10);
            // var conditon = BaseModel.checkLimit(HeartModel.client, conf.limit);

            // O1Test.test(HeartModel.client);


            // var res = await MaoSocket.asyncToken(3122) as CROSS_BATTLE_MOVIE;
            // var movie = res.movie.ReadObject();

            var req = new rank_formation_req();
            req.heros = new List<Hero_put_req>();

            var put = new Hero_put_req();
            put.id = 42;
            put.pos = 8;
            req.heros.Add(put);

            put = new Hero_put_req();
            put.id = 63;
            put.pos = 10;
            req.heros.Add(put);

            // UInt64 a =0;

            put = new Hero_put_req();
            put.id = 66;
            put.pos = 12;
            req.heros.Add(put);
            rank_formation_rsp atk = await MaoSocket.asyncToken(RankSocketConst.formation, req) as rank_formation_rsp;




            var ttt = await MaoSocket.asyncToken(RankSocketConst.match_list, req);


            // mine_get_all_mine_res res = await MaoSocket.asyncToken(MineSocketConst.get_all_mine, null) as mine_get_all_mine_res;

            Console.WriteLine("??");




            // Random rd = new Random();
            // SetInterval(500, async (e) =>
            // {
            //     await setProperty("res.money1", rd.Next(1, 100));
            // });





            Console.WriteLine("??");
        }






        public async static Task Hero_Test()
        {
            var get_value = new Hero_get_req();
            List<Hero_put_req> reqs = new List<Hero_put_req>();
            for (ushort i = 1; i < 5; i++)
            {
                get_value.id = i;
                Hero_put_req put_value = new Hero_put_req();
                put_value.id = i;
                put_value.pos = (short)i;
                reqs.Add(put_value);
                await MaoSocket.asyncToken(HeroSocketConst.hero_get, get_value);
            }
            var v = await MaoSocket.asyncToken(HeroSocketConst.Hero_put_all, reqs);
            Console.WriteLine("Hero_Test");
        }

        public async static Task ChapterTest()
        {
            Chapter_Fight_req req = new Chapter_Fight_req();
            req.id = 1;
            req.lv = 1;
            var atk = await MaoSocket.asyncToken(ChapterSocketConst.Chapter_Fight, req);//as Chapter_Fight_atk;
            Console.WriteLine("ChapterTest");
        }



        public async static Task<object> setProperty(string key, object value)
        {
            var pros = key.Split(".");
            var o = new ASObject();
            var p = o;
            for (var i = 0; i < pros.Length - 1; i++)
            {
                var pro = pros[i];
                var newobj = new ASObject();
                o[pro] = newobj;
                o = newobj;
            }
            o[pros[pros.Length - 1]] = value;
            return await MaoSocket.asyncToken(1, p);

        }


        /**
            gm指令
            await command("item_create", 1, 2);
        */
        public async static Task<object> command(string cmd, params object[] value)
        {
            return await MaoSocket.asyncToken(3, new object[] { cmd, value });
        }







        public static void SetInterval(double interval, Action<ElapsedEventArgs> action)
        {
            Timer timer = new Timer(interval);
            timer.Elapsed += delegate (object sender, ElapsedEventArgs e)
            {
                action(e);
            };
            timer.Enabled = true;
        }

        public static void SetTimeout(double interval, Action action)
        {
            Timer timer = new Timer(interval);
            timer.Elapsed += delegate (object sender, ElapsedEventArgs e)
            {
                timer.Enabled = false;
                action();
            };
            timer.Enabled = true;
        }
    }
}

